#!/bin/bash

# 设置环境变量
export UESTUDIO="/d/vc/UEStudio"
export UESTUDIO_SRC="$UESTUDIO/src"
export wxWIN="/d/vc/wxWidgets-3.2.7"
export wxINCLUDE="$wxWIN/include"
export wxSETUP_H="$wxWIN/lib/wx/include/msw-unicode-3.2"
export wxLIB_DLL="$wxWIN/lib"

export CXXFLAGS="-I. -I$UESTUDIO_SRC/include -I$UESTUDIO_SRC/sdk/wxscintilla/include -I$wxINCLUDE -I$wxSETUP_H -D__WXMSW__ -DcbDEBUG -DWXUSINGDLL -std=c++17"
export LDFLAGS="-L$wxLIB_DLL -L$UESTUDIO_SRC/devel"

echo "🚀 AICoder 插件编译开始 (详细模式)..."
echo "=========================================="

# 显示编译环境
echo "编译环境:"
echo "CXXFLAGS: $CXXFLAGS"
echo "LDFLAGS: $LDFLAGS"

# 清理旧文件
echo "清理旧编译文件..."
find . -name "*.o" -delete
rm -f AICoder.dll

# 详细编译函数
compile_file_verbose() {
    local file=$1
    echo "=========================================="
    echo "编译: $file"
    echo "命令: g++ $CXXFLAGS -c \"$file\" -o \"${file%.cpp}.o\""
    g++ $CXXFLAGS -c "$file" -o "${file%.cpp}.o"
    local result=$?
    if [ $result -eq 0 ]; then
        echo "✅ $file 编译成功"
        return 0
    else
        echo "❌ $file 编译失败 (退出码: $result)"
        return 1
    fi
}

# 先单独测试第一个文件，显示完整错误
echo "=========================================="
echo "详细测试第一个文件编译..."
compile_file_verbose "CollaborativeCore/CollaborationProtocol.cpp"

# 如果第一个文件失败，停止并显示帮助信息
if [ $? -ne 0 ]; then
    echo ""
    echo "🔧 编译问题诊断:"
    echo "1. 检查头文件路径是否存在:"
    echo "   ls -la \"$UESTUDIO_SRC/include/cbplugin.h\""
    echo "   ls -la \"$wxINCLUDE/wx/string.h\""
    echo ""
    echo "2. 测试简单wx程序编译:"
    echo "   echo '#include <wx/string.h>' > test_wx.cpp"
    echo "   g++ $CXXFLAGS -c test_wx.cpp -o test_wx.o"
    exit 1
fi

# 继续编译其他文件
echo "=========================================="
echo "继续编译其他文件..."
compile_file_verbose "CollaborativeCore/RealTimeEditor.cpp" || exit 1
compile_file_verbose "ModelModuleSystem/ModelComponent.cpp" || exit 1
compile_file_verbose "ModelModuleSystem/ComponentAssembler.cpp" || exit 1
compile_file_verbose "GlobalRegistry/ComponentRegistry.cpp" || exit 1

echo "=========================================="
echo "编译主插件..."
compile_file_verbose "AICoder.cpp" || exit 1

echo "=========================================="
echo "链接生成DLL..."
if g++ -shared -o AICoder.dll \
    CollaborativeCore/*.o \
    ModelModuleSystem/*.o \
    GlobalRegistry/*.o \
    AICoder.o \
    $LDFLAGS \
    -lcodeblocks -lwx_mswu_core-3.2 -lwx_baseu-3.2; then
    
    echo "✅ AICoder.dll 链接成功！"
    ls -lh AICoder.dll
    
    # 部署
    mkdir -p "$UESTUDIO/output/plugins"
    cp AICoder.dll "$UESTUDIO/output/plugins/" && echo "✅ 插件已部署"
    
else
    echo "❌ 链接失败"
    exit 1
fi

echo "=========================================="
echo "🎉 AICoder 插件编译完成！"
